#include "stm32f4xx.h"  
#include "usart3.h"     
#include "led.h"
#include "beep.h"
#include "picture.h"

#if  USART3_RX_ENABLE                   
char Usart3_RxCompleted = 0;//Rx-->receive             
unsigned int Usart3_RxCounter = 0;      
char Usart3_RxBuff[USART3_RXBUFF_SIZE];   	
#endif

UART_HandleTypeDef USART3_Handler; 
void usart3_init(int bound)
{
    USART3_Handler.Instance=USART3;					    
    USART3_Handler.Init.BaudRate=bound;				    
    USART3_Handler.Init.WordLength=UART_WORDLENGTH_8B;  
    USART3_Handler.Init.StopBits=UART_STOPBITS_1;	    
    USART3_Handler.Init.Parity=UART_PARITY_NONE;		
    USART3_Handler.Init.HwFlowCtl=UART_HWCONTROL_NONE;  
    USART3_Handler.Init.Mode=UART_MODE_TX_RX;		    
    HAL_UART_Init(&USART3_Handler);					    
    GPIO_InitTypeDef GPIO_InitStruct = {0};
    __HAL_RCC_USART3_CLK_ENABLE();

    __HAL_RCC_GPIOB_CLK_ENABLE();
    /**USART3 GPIO Configuration
      PB10     ------> USART3_TX
      PB11     ------> USART3_RX
      */
    GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_NOPULL;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF7_USART3;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);

    HAL_NVIC_SetPriority(USART3_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USART3_IRQn);

    USART3->CR1|=1<<3;  	
    USART3->CR1|=1<<2;  	
    USART3->CR1|=1<<5;    	
    USART3->CR1|=1<<13;  
}

char Usart3_TxBuff[USART3_TXBUFF_SIZE];  
//__align(8) char Usart3_TxBuff[USART3_TXBUFF_SIZE];  

void u3_printf(char* fmt,...) 
{  
    unsigned int i,length;

    va_list ap;
    va_start(ap,fmt);
    vsprintf(Usart3_TxBuff,fmt,ap);
    va_end(ap);	

    length=strlen((const char*)Usart3_TxBuff);		
    while((USART3->SR&0X40)==0);
    for(i = 0;i < length;i ++)
    {			
        USART3->DR = Usart3_TxBuff[i];
        while((USART3->SR&0X40)==0);	
    }	
}

//Control the peripherals based on the data from the serial port
void usart3_receive_msg_handler(char *receive_str)
{
    //led msg handler
    drv_led_usart_receive_msg_handler(receive_str);
    
    //beep msg handler
    drv_beep_usart_receive_msg_handler(receive_str);

    //picture msg handler
    drv_picture_usart_receive_msg_handler(receive_str);
}
